const express=require('express');
const bodyParser=require('body-parser');
const pool=require('./pool');
const cors=require('cors')

//创建web服务器
var app=express();
app.listen(3000);
//使用中间件
app.use(bodyParser.urlencoded({
    extended:false
}));
//解决跨域
app.use(cors({
    origin:['http://localhost:8080','http://127.0.0.1:8080'],
    credentials:true
}))


//登录
app.get('/login',(req,res)=>{
    var uname=req.query.uname;
    var upwd=req.query.upwd;
    var sql='SELECT COUNT(uid) as c FROM user WHERE uname=? and upwd=?';
    pool.query(sql,[uname,upwd],(err,result)=>{
        if(err) throw err;
        console.log(result);
        if(result[0].c==0){
            res.send({code:-1,msg:'账号或密码错误'})
        }else{
            res.send({code:1,msg:'登录成功'})
        }
    })
})

//注册
app.post('/reg',(req,res)=>{
    var obj=req.body;
    var $uname=obj.uname;
    if($uname==''){
        res.send({code:401,msg:'账号不能为空'});
        return;
    }
    //console.log(111);
    var $upwd=obj.upwd;
    if($upwd==''){
        res.send({code:402,msg:'密码不能为空'});
        return;
    }
    //console.log(2222);
    var sql='INSERT INTO user VALUES(NULL,?,?)';
    pool.query(sql,[$uname,$upwd],(err,result)=>{
        console.log('注册成功');
        if(err) throw err;
        if(result.affectedRows>0){
            res.send({code:200,msg:'注册成功'});
        }else{
            res.send({code:300,msg:'注册失败'});
        }
    })
})

